/*
 * Copyright (c) 2008-2011, Petr Panteleyev
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *    3. The name of the author may not be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.panteleyev.blogclient;

import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.io.Serializable;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.KeyStroke;
import org.panteleyev.swing.ClipboardUtil;

/**
 *
 * @author Petr Panteleyev
 */
final class Template implements Comparable<Template>, Serializable {
    private final static long serialVersionUID = 20100307L;

    private static final String DEFAULT_DELIM = "";

    private static final String ARGS = "args";
    private static final String WHOLE_TEXT = "arg0";
    private static final String CLIPBOARD_PARAM = "clipboard";
    private static final String RESULT = "result";

    private String name = "";
    private String description = "";
    private String body = "";
    private String delimiter = DEFAULT_DELIM;

    /* Hot key */
    private int keyCode;
    private int modifiers;

    public Template() {
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public String getDelimiter() {
        return delimiter;
    }

    public void setDelimiter(String delimiter) {
        this.delimiter = delimiter;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getKeyCode() {
        return keyCode;
    }

    public void setKeyCode(int keyCode) {
        this.keyCode = keyCode;
    }

    public int getModifiers() {
        return modifiers;
    }

    public void setModifiers(int modifiers) {
        this.modifiers = modifiers;
    }

    public KeyStroke getHotKey() {
        return (keyCode == 0)? null : KeyStroke.getKeyStroke(keyCode, modifiers);
    }

    @Override
    public int compareTo(Template t) {
        return getName().compareTo(t.getName());
    }

    /**
     * Parameters:<br>
     * <li>{%N} - N argument
     * <li>{%0} - the whole selection
     * @param text
     * @return processed text
     */
    public String apply(String text) throws ScriptException {
        if (text == null) {
            text = "";
        }

        String args[] = text.split(delimiter);

        ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
        if (engine == null) {
            return text;
        }

        Bindings params = engine.createBindings();
        params.put(WHOLE_TEXT, text);
        params.put(ARGS, args);

        // Get text from clipboard
        String clText = null;
        try {
            clText = ClipboardUtil.getAsString();
        } catch (UnsupportedFlavorException | IOException ex) {
            // do nothing, just leave an empty string
        }

        params.put(CLIPBOARD_PARAM, (clText == null)? "" : clText);

        engine.setBindings(params, ScriptContext.ENGINE_SCOPE);
        engine.eval(body);

        Object result = params.get(RESULT);
        if (result == null) {
            return text;
        } else {
            return result.toString();
        }
    }

}
